﻿package net.wangit.adm.org;

import net.wangit.Element;
import net.wangit.MapList;
import net.wangit.Unit;
import net.wangit.context.ActionContext;
import net.wangit.jdbc.DB;
import net.wangit.jdbc.DBFactory;
import net.wangit.support.UnitInterceptor;
import net.wangit.util.Checker;
import net.wangit.view.tree.TreeUtil;

public class OrgUI implements UnitInterceptor {

	private static final String SQL_PARENT = "select orgid as value ,orgname as name,parentid,o from AORG where orgid!=? order by o";
	private static final String SQL_PARENT_ADD = "select orgid as value ,orgname as name,parentid,o from AORG order by o";

	public OrgUI() {
	}

	public String intercept(ActionContext ac, Unit unit) throws Exception {
		MapList data = unit.getData();
		if (!Checker.isEmpty(data)
				&& Checker.isEmpty(data.getRow(0).get("parentid"))) {
			unit.removeElement("parentid");
		} else {
			String unitShowMode = unit.getShowMode();
			DB db = DBFactory.getDB();
			String orgId = Checker.isEmpty(data) ? "" : data.getRow(0).get(
					"orgid");
			MapList list;
			if ("a".equals(unitShowMode))
				list = db
						.query("select orgid as value ,orgname as name,parentid,o from AORG order by o");
			else
				list = TreeUtil
						.filterParentId(
								db,
								"select orgid as value ,orgname as name,parentid,o from AORG where orgid!=? order by o",
								orgId, "parentid", 2);
			Element element = unit.getElement("parentid");
			element.setObject(list);
			if ("a".equals(unitShowMode))
				element.setDefaultValue(ac.getRequestParameter("parentid"));
		}
		return unit.write(ac);
	}
}
